import uuid

from framework.BaseService import BaseService
from framework.EException import EException
import datetime;

class MemberService(BaseService):


    def getFavoriteCount(self,memberId):
        sql="select count(id) cnt from  bis_collecting where member_id='"+memberId+"'";
        entity=self.mySql.selectOne(sql);
        return entity["cnt"];

    def getPlayCount(self,memberId):
        sql="SELECT SUM(play_count) cnt FROM bis_playhistory where member_id='"+memberId+"'";
        entity=self.mySql.selectOne(sql);
        return entity["cnt"];

    #会员登录
    def login(self,postData):
        if (postData["name"] == None or postData["name"] == "" or postData["name"] == "null"):
            memberInfo = self.mySql.selectOne("select * from bis_member where id='" + postData["id"]+"'");
            if (memberInfo == None):
                return {
                    "code": 503,
                    "message": "用户不存在，请先进行注册。"
                };
            if (memberInfo["pwd"] != None):
                if (postData["pwd"] != memberInfo["pwd"]):
                    return {
                        "code": 502,
                        "message": "用户名密码错误，请重新输入。"};
            sql = "update bis_member set device_id='{0}',last_login=now(),ver_code='{1}',ver_name='{2}' where id='{3}'".format(
                postData["deviceId"], postData["verCode"], postData["verName"], postData["id"]
            );
            self.mySql.execute(sql);
            postData["favorite"]=self.getFavoriteCount(memberInfo["id"]);
            postData["listenCount"] = self.getPlayCount(memberInfo["id"]);
            return postData;
        else:
            memberInfos = self.mySql.select("select * from bis_member where name='" + postData["name"]+"'");
            if (memberInfos==None):
                return {
                    "code": 503,
                    "message": "用户不存在，请先进行注册。"
                };
            #设备ID不同，换手机，密码一致可登录，并合并信息
            for member in memberInfos:
                if (member["id"]==postData["id"]):
                    if (memberInfos[0]["pwd"]!= None):
                        if (memberInfos[0]["pwd"]!=postData["pwd"]):
                            return {
                                "code":502,
                                "message": "用户名密码错误，请重新输入。"
                            };
                    sql = "update bis_member set device_id='{0}',last_login=now(),ver_code='{1}',ver_name='{2}' where id='{3}'".format(
                        postData["deviceId"], postData["verCode"], postData["verName"], postData["id"]
                    );
                    self.mySql.execute(sql);
                    postData["favorite"] = self.getFavoriteCount(member["id"]);
                    postData["listenCount"] = self.getPlayCount(member["id"]);
                    return postData;

            return {
                "code": 503,
                "message": "用户不存在，请先进行注册。"
            };

    # 会员注册
    def register(self, member):
        try:
            self.checkJsonKey(member,"deviceId","loginType");
            memberInfo=self.mySql.selectOne("select * from bis_member where device_id='"+member["deviceId"]+"'");
            if (memberInfo == None):
                memberInfo=member;
                memberInfo["id"]=str(uuid.uuid1()).replace("-","");
                memberInfo["reg_date"]=datetime.datetime.now();
                memberInfo["last_login"]=datetime.datetime.now();
                memberInfo["valid_date"]=datetime.datetime.now()+datetime.timedelta(days=30);
                self.mySql.insert("bis_member", member);
                memberInfo["favorite"] = 0;
                memberInfo["listenCount"] = 0;
                return member;
            else:
                memberInfo["last_login"] = datetime.datetime.now();
                self.mySql.update("bis_member","id",memberInfo);
                memberInfo["favorite"] = self.getFavoriteCount(memberInfo["id"]);
                memberInfo["listenCount"] = self.getPlayCount(memberInfo["id"]);
                return memberInfo;
        except EException as e:
            {
                "code": e.ErrCode(),
                "message": "用户不存在，请先进行注册。"
            };

    def __addMyMusicList(self,musicItem):
        sql="select * from bis_musiclist where mymusic_id='%s' and music_id='%s'" %(
            musicItem["mymusic_id"],musicItem["music_id"]
        );
        item= self.mySql.selectOne(sql);
        if (item!=None):
            return True;
        sql = "select * from bis_musiclist where mymusic_id='%s' order by sort limit 1" % (
            musicItem["mymusic_id"]
        );
        item=self.mySql.selectOne(sql);
        if (item==None):
            musicItem["sort"]=0;
        else:
            musicItem["sort"] =item["sort"]+1;
        musicItem["create_time"]=datetime.datetime.now();
        return self.mySql.insert("bis_musiclist",musicItem);

    #添加会员歌单明细
    def addMyMusicItem(self,postData,memberInfo):
        musicItem = postData["itemInfo"];
        music = postData["musicInfo"];
        dbmusic=self.mySql.selectOne("select * from bis_music where ext_info='"+ music["songId"]+"'");
        if (dbmusic == None):
            self.mySql.insert("bis_music",music);
            dbmusic=music;
        musicItem["music_id"]=dbmusic["id"];
        self.mySql.insert("")
        if (self.addMyMusicList(musicItem)):
            return musicItem;
        else:
            raise EException(501, "添加歌曲失败");

    def getMyMusicList(self,memberId,pageIndex,pageSize):
        sql="SELECT *, (SELECT COUNT(*) FROM bis_musiclist WHERE mymusic_id=a.id) music_count " \
        "FROM  `bis_mymusic` a " \
        "WHERE a.`member_id`='"+memberId+"' order by a.name ,a.create_time desc";
        return self.mySql.selectPage(sql,pageIndex,pageSize);

    #会员列表
    def memberList(self,info,pageIndex,pageSize):
        sql="select * from bis_member"
        return self.mySql.selectPage(sql,pageIndex,pageSize);

    #由会员Id获取信息
    def getById(self,id):
        sql = "select * from bis_member where id='{0}'".format(id);
        return self.mySql.selectOne(sql);